import { storage, baseURL } from '@/config/index';
import { getDictListByCodeParams } from '@/api/system/dict/dictManagement';
import request from '@/utils/request';

// 缓存前缀 方便统一删除处理
const cachePrefix = 'opsli:dict';

// 字典项接口
export interface DictItem {
  dictName: string;
  dictValue: string;
  [key: string]: any;
}

/**
 * 获得前端本地缓存
 */
function getCache(): Record<string, DictItem[]> | null {
  let cache: string | null = null;

  if (storage === 'localStorage') {
    cache = localStorage.getItem(cachePrefix);
  } else if (storage === 'sessionStorage') {
    cache = sessionStorage.getItem(cachePrefix);
  } else {
    cache = localStorage.getItem(cachePrefix);
  }

  return cache ? JSON.parse(cache) : null;
}

/**
 * 设置前端本地缓存
 */
function setCache(cache: Record<string, DictItem[]>): void {
  const json = JSON.stringify(cache);

  if (storage === 'localStorage') {
    localStorage.setItem(cachePrefix, json);
  } else if (storage === 'sessionStorage') {
    sessionStorage.setItem(cachePrefix, json);
  } else {
    localStorage.setItem(cachePrefix, json);
  }
}

/**
 * 移除缓存
 */
function removeCache(): void {
  if (storage === 'localStorage') {
    localStorage.removeItem(cachePrefix);
  } else if (storage === 'sessionStorage') {
    sessionStorage.removeItem(cachePrefix);
  } else {
    localStorage.removeItem(cachePrefix);
  }
}

/**
 * 存储字典
 */
function setDictList(typeCode: string, dictList: DictItem[]): void {
  let cache = getCache();
  if (!cache) {
    cache = {};
  }

  cache[typeCode] = dictList;
  setCache(cache);
}

/**
 * 获取字典列表 - 同步版本（仅从缓存获取）
 */
export function getDictListSync(typeCode: string): DictItem[] {
  let cache = getCache();
  if (!cache) {
    console.log('远程更新字典', typeCode);

    updateDictList(typeCode).then(r => { });
    return [];
  }
  //如果缓存没有，则去远端获取
  if (!cache[typeCode]) {

    updateDictList(typeCode).then(r => { });
  }

  return cache[typeCode] || [];
}

/**
 * 
 * @param typeCode 从服务器更新字典列表
 * @returns 
 */
export async function updateDictList(typeCode: string): Promise<DictItem[]> {
  const { data } = await request({
    url: '/api/v1/system/dict/getDictListByCode',
    method: 'get',
    params: { typeCode }
  });
  setDictList(typeCode, data);
  return data;
}

/**
 * 根据字典值获取字典名称 - 同步版本（仅从缓存获取）
 */
export function getDictNameByValueSync(typeCode: string, dictValue: string): string | null {
  const dictList = getDictListSync(typeCode);
  const dictItem = dictList.find(item => item.dictValue === dictValue);
  return dictItem ? dictItem.dictName : null;
}

/**
 * 根据字典名称获取字典值 - 同步版本（仅从缓存获取）
 */
export function getDictValueByNameSync(typeCode: string, dictName: string): string | null {
  const dictList = getDictListSync(typeCode);
  const dictItem = dictList.find(item => item.dictName === dictName);
  return dictItem ? dictItem.dictValue : null;
}

/**
 * 获取字典列表
 */
export async function getDictList(typeCode: string): Promise<DictItem[]> {
  let cache = getCache();
  if (!cache) {
    cache = {};
  }

  let dictList = cache[typeCode];

  // 如果本地缓存没有，则去远端获取
  if (!dictList || dictList.length === 0) {
    try {
      const { data } = await request({
        url: '/api/v1/system/dict/getDictListByCode',
        method: 'get',
        params: { typeCode }
      });
      setDictList(typeCode, data);
      return data;
    } catch (error) {
      console.error('获取字典失败:', error);
      return [];
    }
  }

  return dictList || [];
}

/**
 * 根据字典名称获取字典值
 */
export async function getDictValueByName(typeCode: string, dictName: string): Promise<string | null> {
  const dictList = await getDictList(typeCode);
  const dictItem = dictList.find(item => item.dictName === dictName);
  return dictItem ? dictItem.dictValue : null;
}

/**
 * 根据字典值获取字典名称
 */
export async function getDictNameByValue(typeCode: string, dictValue: string): Promise<string | null> {
  console.log(typeCode, dictValue);
  const dictList = await getDictList(typeCode);
  const dictItem = dictList.find(item => item.dictValue === dictValue);
  console.log(dictItem);
  return dictItem ? dictItem.dictName : null;
}

/**
 * 清空字典缓存
 */
export function clearDictList(): void {
  removeCache();
}

// 字典工具类
export class DictUtils {
  /**
   * 获取字典列表
   */
  static async getDictList(typeCode: string): Promise<DictItem[]> {
    return getDictList(typeCode);
  }

  /**
   * 根据字典名称获取字典值
   */
  static async getDictValueByName(typeCode: string, dictName: string): Promise<string | null> {
    return getDictValueByName(typeCode, dictName);
  }

  /**
   * 根据字典值获取字典名称
   */
  static async getDictNameByValue(typeCode: string, dictValue: string): Promise<string | null> {
    return getDictNameByValue(typeCode, dictValue);
  }

  /**
   * 清空字典缓存
   */
  static clearDictList(): void {
    clearDictList();
  }
}

export default DictUtils; 